package ch.upndown.upndown;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import ch.upndown.upndown.model.Website;
import ch.upndown.upndown.utils.IconAsyncTask;

/**
 * Created by Bernard on 01.08.2014.
 */
public class OverviewAdapter extends ArrayAdapter<Website> {
    private final int resourceId;
    private final List<Website> objects;


    public OverviewAdapter(Context context, List<Website> objects) {
        super(context, R.layout.row_website, objects);
        resourceId = R.layout.row_website;
        this.objects = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
            row = inflater.inflate(resourceId, parent, false);
        }

        ImageView icon = (ImageView) row.findViewById(R.id.website_image);
        try {
            URL url = new URL("http://www.uefa.com/imgml/favicon/comp/uefacup.ico");
            new IconAsyncTask(icon, url).execute();
        } catch (MalformedURLException e) {
            icon.setImageResource(R.drawable.ic_launcher);
        }

        TextView title = (TextView) row.findViewById(R.id.website_title);
        title.setText(objects.get(position).getTitle());

        TextView url = (TextView) row.findViewById(R.id.website_url);
        url.setText(objects.get(position).getUrl());

        return row;
    }
}
